package com.chen.manager;

import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.chen.bean.constants.QwenModelConstants;
import com.chen.bean.enums.ResultCode;
import com.chen.config.QwenConfig;
import com.chen.exception.BusinessException;
import io.reactivex.Flowable;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class QwenManager {

    @Autowired
    private Generation gen;

    @Autowired
    private QwenConfig qwenConfig;


    /**
     * 调用通义千文 聊天接口，以流式输出
     * @param messageList
     * @return
     */
    public Flowable<GenerationResult> qwenStreamCall(List<Message> messageList) throws BusinessException {
        //构建参数
        GenerationParam param = buildGenerationParam(messageList);
        //调用SDK
        Flowable<GenerationResult> result;
        try {
            result = gen.streamCall(param);
        } catch (NoApiKeyException | InputRequiredException e) {
            throw new BusinessException(ResultCode.INTERNAL_SERVER_ERROR.getCode(),e.getMessage());
        }
        return result;
    }

    //构建访问参数
    public GenerationParam buildGenerationParam(List<Message> messageList) {
        return GenerationParam.builder()
                // 若没有配置环境变量，请用百炼API Key将下行替换为：.apiKey("sk-xxx")
                .apiKey(qwenConfig.getApiKey())
                .model(QwenModelConstants.MAX)
                .messages(messageList)
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .incrementalOutput(true)    //增量输出
                .build();
    }
}
